//
//  YYEncryptonVC.m
//  Pthread
//
//  Created by Yanyan Jiang on 2025/3/5.
//  Copyright © 2025 Yanyan Jiang. All rights reserved.
//

#import "YYEncryptionVC.h"
#import "AESUtil.h"
#import "YYImageCryptoManager.h"
#import "NSData+Hash.h"
#import "NSString+Hash.h"
#import "RSACryptor.h"

@interface YYEncryptionVC ()
@property (weak, nonatomic) IBOutlet UIImageView *encryptionIV;
@property (weak, nonatomic) IBOutlet UIImageView *decryptionIV;

@property(strong, nonatomic)NSData *key;
@property(strong, nonatomic)NSData *iv;
@property(strong, nonatomic)NSString *encryptionPath;
@property(strong, nonatomic) NSData *publicData;
@end

@implementation YYEncryptionVC

- (void)viewDidLoad {
    [super viewDidLoad];
}


//生成密钥、初始化向量
- (void)keyAndInitializationVector{
    // 生成密钥和 IV
//    self.key = [AESUtil generateAES256Key];
    self.iv = [AESUtil generateIV];
    
    // 加密示例 (原始客串任意长度)
    NSString *inputString = @"168.192.50.10xingchenhuanyu"; // 确保密钥为32字节
    //生成SHA256 哈希密钥（32字节）
    NSData *keyData = [inputString sha256Hash];
    self.key = keyData;
    
    
    
    //如果需要将密钥以十六进制字符串形式查看
//    NSString *hexKey = [keyData description];
    //输出结果
    NSLog(@"SHA256 密钥长度: %lu 字节",(unsigned long)keyData.length);
    NSLog(@"密钥数据：%@ ",keyData);
}



//图片加密
- (void)pictureEncryption{
    //01 获得文件夹的路径
    NSString *from = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CG";
    NSString *to = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CGEncryption";
    //02 获得该文件夹下面的所有文件
    NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:from];
    NSString *originalPath = [NSString stringWithFormat:@"%@/%@",from,subPaths[0]];;
    
    UIImage *originalImage = [UIImage imageWithContentsOfFile:originalPath];
    self.encryptionIV.image = originalImage;
    

    
    //    NSString *key = @"我是32位的密钥xxxxxxxxxxxxxxxx";
    //    NSString *iv = @"16字节长度的IVxxx";                  // 确保IV为16字节
    //    使用SHA256哈希将任意长度的字符串转换为32字节的密钥。
    
    //加密原始图片
    NSData *encryptedData = [YYImageCryptoManager encryptImage:originalImage key:self.key iv:self.iv];
    //把加密后的图片以二进制文件存储到桌面
    self.encryptionPath = [to stringByAppendingPathComponent:@"01.bin"];
    [encryptedData writeToFile:self.encryptionPath atomically:YES];
}

//图片解密
- (void)pictureDecryption{
    //从桌面读取加密后的图片
    NSData *readEncryptionData = [NSData dataWithContentsOfFile:self.encryptionPath];
    // 解密图片并展示
    UIImage *decryptedImage = [YYImageCryptoManager decryptImageData:readEncryptionData key:self.key iv:self.iv];
    self.decryptionIV.image = decryptedImage;
}


#pragma mark -- addTarget
//加密
- (IBAction)pictureEncryption:(id)sender {
    [self keyAndInitializationVector];
    [self pictureEncryption];
}


//解密
- (IBAction)pictureDecrypt:(id)sender {
    [self pictureDecryption];
}


//公钥加密
- (IBAction)publicKeyEncrypt:(id)sender {
    //01 加载公钥
    [[RSACryptor sharedRSACryptor] loadPublicKey:[[NSBundle mainBundle] pathForResource:@"rsacert.der" ofType:nil]];
    //02 对数据加密
    NSData *data = [[RSACryptor sharedRSACryptor] encryptData:[@"yanyan0303" dataUsingEncoding:NSUTF8StringEncoding]];
    //对加密得到的密文进行base64编码打印
    NSLog(@"%@",[data base64EncodedStringWithOptions:kNilOptions]);
    self.publicData = data;
}

//私钥解密
- (IBAction)privateKeyDecrypt:(id)sender {
    //03 加载私钥
    [[RSACryptor sharedRSACryptor] loadPrivateKey:[[NSBundle mainBundle] pathForResource:@"private.p12" ofType:nil] password:@"616263"];
    //04 对密文进行解密处理
    NSLog(@"%@",[[NSString alloc]initWithData:[[RSACryptor sharedRSACryptor] decryptData:self.publicData] encoding:NSUTF8StringEncoding]);
}


#pragma mark 文件剪切操作
-(void)moveItem{
    //01 获得文件夹的路径
    NSString *from = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CG";
    NSString *to = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CGEncryption";
    //02 获得该文件夹下面的所有文件
    NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:from];
    NSLog(@"%@",subPaths);
    //03 遍历
    for (int i = 0; i < subPaths.count; ++i) {
        NSString *fileName = subPaths[i];
        //拼接文件的全路径
        ///Users/xiaomage/Desktop/from/Snip20161119_30.png
        NSString *fromFullPath = [from stringByAppendingPathComponent:fileName];
        NSString *toFullPath = [to stringByAppendingPathComponent:fileName];
        //04 执行文件的剪切操作
        /* 参数说明
         *
         * 第一个参数:要剪切的文件在哪里
         * 第二个参数:要剪切到什么地方去(目标路径)
         * 第三个参数:错误信息
         */
        [[NSFileManager defaultManager] moveItemAtPath:fromFullPath toPath:toFullPath error:nil];
//        [[NSFileManager defaultManager] copyItemAtPath:fromFullPath toPath:toFullPath error:nil];
        NSLog(@"%@--%@--%@",fromFullPath,toFullPath,[NSThread currentThread]);
    }
}


-(void)test2{
    //01 获得文件夹的路径
    NSString *from = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CG";
    NSString *to = @"/Users/yanyanjiang/Desktop/xingchenhuanyn/CGEncryption";
    //02 获得该文件夹下面的所有文件
    NSArray *subPaths = [[NSFileManager defaultManager] subpathsAtPath:from];
    NSLog(@"%@",subPaths);
    dispatch_apply(subPaths.count, dispatch_get_global_queue(0, 0), ^(size_t i) {
        NSString *fileName = subPaths[i];
        //拼接文件的全路径
        NSString *fromFullPath = [from stringByAppendingPathComponent:fileName];
        NSString *toFullPath = [to stringByAppendingPathComponent:fileName];
        //执行文件的剪切操作
        [[NSFileManager defaultManager] moveItemAtPath:fromFullPath toPath:toFullPath error:nil];
        NSLog(@"%@--%@--%@",fromFullPath,toFullPath,[NSThread currentThread]);
    });
}


//加密
- (void)textEncryption{
    // 生成密钥和 IV
    NSData *aesKey = [AESUtil generateAES256Key];
    NSData *iv = [AESUtil generateIV];

    // 准备明文数据
    NSString *plainText = @"Hello, AES加密测试!";
    NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];

    // 加密
    NSData *encryptedData = [AESUtil aesEncryptData:plainData key:aesKey iv:iv];
    if (encryptedData) {
        NSLog(@"加密结果: %@", encryptedData);
        
        // 解密
        NSData *decryptedData = [AESUtil aesDecryptData:encryptedData key:aesKey iv:iv];
        if (decryptedData) {
            NSString *decryptedText = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
            NSLog(@"解密结果: %@", decryptedText);
        }
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
